﻿using DDNS.Model.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DDNS.Infrastructure
{
    public static class Tools
    {
        /// <summary>
        /// 验证字符串是否是域名
        /// </summary>
        /// <param name="str">指定字符串</param>
        /// <returns></returns>
        public static bool IsDomain(string str)
        {
            string expression = @"^[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$";
            Regex reg = new Regex(expression);
            if (string.IsNullOrEmpty(str))
                return false;
            return reg.IsMatch(str);// 判断一个字符串，是否匹配指定的表达式(区分大小写的情况下)
        }

        /// <summary>
        /// 获取页面html；从html中通过正则找到ip信息(只支持ipv4地址)
        /// </summary>
        /// <param name="url">请求的地址</param>
        /// <param name="encode">编码方式[Encoding.UTF8]</param>
        /// <returns></returns>
        public static string GetIP(string url, Encoding encode, EnumIPType type)
        {
            string ip = string.Empty;
            try
            {
                string pageHtml = string.Empty;
                using (WebClient MyWebClient = new WebClient())
                {
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
                    Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                    pageHtml = (encode ?? Encoding.UTF8).GetString(pageData);
                    //验证ipv4地址
                    string regipv4 = @"(?:(?:(25[0-5])|(2[0-4]\d)|((1\d{2})|([1-9]?\d)))\.){3}(?:(25[0-5])|(2[0-4]\d)|((1\d{2})|([1-9]?\d)))";
                    //验证ipv6地址
                    string regipv6 = @"^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9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(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d{1,2})|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))))$";
                    Match m;
                    if (type == EnumIPType.IPv4)
                    {
                        m = Regex.Match(pageHtml, regipv4);
                    }
                    else
                    {
                        m = Regex.Match(pageHtml, regipv6);
                    }
                    if (m.Success)
                    {
                        ip = m.Value;
                    }
                    return ip;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取外网IP地址错误：{ex.Message}");
            }
            return ip;
        }
    }
}
